package models.admin;

import models.BaseModel;
import models.enums.TreeNodeStatus;

import javax.persistence.*;
import java.util.List;

/**
 * Created by liming on 16/7/1.
 */
@Entity
@Table(name = "admin_menu_item")
public class AdminMenuItem extends BaseModel {
    /**
     * 菜单名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 父级节点
     */
    @Column(name = "parent_id")
    public Long parentId;

    /**
     * 父亲节点对象
     */
    @Transient
    public AdminMenuItem parent;

    /**
     * 业务
     */
    @ManyToOne
    @JoinColumn(name = "business_id")
    public AdminBusiness business;

    /**
     * 关联业务主Id
     */
    @Column(name = "menu_id")
    public Long menuId;

    /**
     * 主业务菜单对象
     */
    @Transient
    public AdminMenu menu;

    /**
     * 是否叶子节点
     */
    @Column(name = "is_leaf")
    public Boolean isLeaf;

    /**
     * 为了控件展示提供的标示叶子节点的字段
     */
    @Transient
    public TreeNodeStatus state;

    /**
     * 排序号
     */
    @Column(name = "show_order")
    public Integer showOrder = 0;

    /**
     * 子节点
     */
    @Transient
    public List<AdminMenuItem> childrenList;

    /**
     * 加载孩子节点
     *
     * @param menuItemId
     * @return
     */
    public static List<AdminMenuItem> loadChildMenuItem(long menuId, long menuItemId) {
        List<AdminMenuItem> menuList = AdminMenuItem.find("menuId = ? and parentId = ? order by showOrder,id desc", menuId, menuItemId).fetch();
        for (AdminMenuItem menu : menuList)
            menu.state = menu.isLeaf != null && menu.isLeaf ? TreeNodeStatus.open : TreeNodeStatus.closed;
        return menuList;
    }

    /**
     * 删除菜单
     *
     * @param
     */
    public static void deleteMenuItems(Long[] deleteMenuItemList) {
        for (Long menuItemId : deleteMenuItemList) {
            AdminMenuItem menuItem = AdminMenuItem.findById(menuItemId);
            long parentId = menuItem.parentId;
            menuItem.delete();
            Long brotherQty = AdminMenuItem.loadBrotherQty(parentId);
            if (brotherQty == 0) {
                AdminMenuItem parent = AdminMenuItem.findById(parentId);
                if(parent!=null){
                    parent.isLeaf = true;
                    parent.save();
                }
            }
        }

    }

    /**
     * 获取兄弟节点个数
     *
     * @param parentId
     * @return
     */
    public static long loadBrotherQty(long parentId) {
        return AdminMenuItem.count("parentId = ?", parentId);
    }
}
